package cn.fff.common.utils;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import io.jsonwebtoken.*;

import java.util.Date;

public class JwtHelper {
    // token 过期时间
    private static final long tokenExpiration = 365 * 24 * 60 * 60 * 1000L;
    // private static long tokenExpiration = 3 * 1000L;
    // 加密秘钥
    private static final String tokenSignKey = "123456";

    // 根据用户id和用户名称生成 token
    public static String createToken(String userId, String username) {
        String token = Jwts.builder()
                .setSubject("AUTH-USER") // 设置分类/组名
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration)) // 设置过期时间
                .claim("userId", userId) // 有效载荷
                .claim("username", username) // 有效载荷
                .signWith(SignatureAlgorithm.HS512, tokenSignKey) // 加密
                .compressWith(CompressionCodecs.GZIP)
                .compact();
        return token;
    }

    public static String getUserId(String token) {
        if (StringUtils.isBlank(token)) return null;
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        return (String) claims.get("userId");
    }

    public static String getUsername(String token) {
        if (StringUtils.isEmpty(token)) return null;
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        String username = (String) claims.get("username");
        return username;
    }
}
